<?php
/**
* Model Class
* 
* @author Guillermo Landín
* @link 
*/ 

class Usermodel extends Model {

    function __construct()
    {
        parent::Model();
        
        $this->CI =& get_instance(); 
    }
    
    /**
    * Check if user credentials are valid
    *
    * @access public
    * @param string
    * @return boolean
    */ 
    function check_valid_user($username,$password)
    {

        $this->db->select('id_Users AS id, UserName_Users AS username')
                ->from('users')
                ->where('UserName_Users', $username)    
                ->where('UserPassword_Users', sha1($password))
                ->where('Active_Users', 1);

        $query = $this->db->get();
        $result = $query->row_array();

        if (empty($result)) {

            return FALSE;

        } else {

            return $result;

        }
        
    }
    /**
    * Check if user credentials are valid
    *
    * @access public
    * @param string
    * @return boolean
    */ 
    function check_valid_user_byid($userid,$password)
    {

        $this->db->select('id_Users AS id, UserName_Users AS username')
                ->from('users')
                ->where('id_Users', $userid)    
                ->where('UserPassword_Users', sha1($password))
                ->where('Active_Users', 1);

        $query = $this->db->get();
        $result = $query->row_array();

        if (empty($result)) {

            return FALSE;

        } else {

            return TRUE;

        }
        
    }
    
    /**
    * Register session vars for user
    *
    * @access public
    * @param string
    * @return boolean
    */ 
/*    function login_user($user_data)
    {

            //register session variables to use in system
            $this->session->set_userdata('user_login', TRUE);
            $this->session->set_userdata('user_id', $user_data['id']);
            $this->session->set_userdata('user_username', $user_data['username']);
            //$this->session->set_userdata('admin_role', $this->valid_user['role']);
        
    }
*/
    /**
    * Destroy session vars
    *
    * @access public
    * @param 
    * @return string
    */ 
    function logout()
    {
        $this->session->unset_userdata('user_login');
        $this->session->unset_userdata('user_id');
        $this->session->unset_userdata('user_username');
        
        @session_unset();
        @session_destroy();
     }

    /**
    * Check if user is logged in
    *
    * @access public
    * @param 
    * @return boolean
    */ 
    function user_login_check()
    {
        if ($this->session->userdata('user_login'))
        return TRUE;
        else 
        return FALSE;
        
    }
         

    public function create_new_user($data_array)
    {

        $sql = $this->db->insert_string('users', $data_array);
        return $this->db->query($sql);

    }       

    public function insert_user_details($data_array)
    {

        $sql = $this->db->insert_string('usersdetails', $data_array);
        return $this->db->query($sql);

    }        

    public function register_user_login($id=false)
    {
        $query = "UPDATE usersdetails SET LastLogin_UsersDetails='".date("Y-m-d H:i:s")."', NumberLogins_UsersDetails = (NumberLogins_UsersDetails+1) WHERE id_Users = '".$id."'";
        $this->db->query($query);
    }       


    /**
    * Is duplicated value?
    * 
    * @access public
    * @param string $field - Field to be searched
    * @param string $value 
    * @return boolean - true is it is a duplicated value
    */
    public function is_duplicated($field, $value)
    {
        $sql = "SELECT count(1) as counter FROM users WHERE " . $field . "=?";
    
        $query = $this->db->query($sql, array($value));
        $row = $query->row_array();
        if($row == NULL)
            return FALSE;
        
        if($row["counter"] > 0){
            return TRUE;
        }else{
            return FALSE;
        }

    }         


    function get_user_from_email($email = FALSE)
    {

         $this->db->select('id_Users AS id')
                ->from('users')
                ->where('UserName_Users', $email);

        $query = $this->db->get();
        $result = $query->row_array();

        return empty($result) ? FALSE : $result['id'];

    }
    function set_new_password($id = FALSE, $password = FALSE)
    {

         $this->db->set('UserPassword_Users', $password)
                ->from('users')
                ->where('id_Users', $id);

        $query = $this->db->update();   

    }                             
 
    function get_user_details($id = NULL) 
    {

        $this->db->select('*')
                ->from('usersdetails')
                ->where('id_Users', $id);

        $query = $this->db->get();
        $result = $query->row_array();

        return empty($result) ? FALSE : $result;
        
    }
	
	// Method: update_user_details
	// UPDATES THE TABLE USERS DETAILS BASED ON A PAIR FIELD NAME / FIELD VALUR FILTERD BY ID USERS
	// CreatedBy: Jonnas
	// Created: 05/06/2013
	
	function update_user_details($dataarray)
	{
		
		//MAPPING HTML INPUT FIELDS TO DATABASE
		//************************************************
		//************ !!! ATTENTION !!! *****************
		//*** IF HTML FIELDS CHANGE THIS HAS TO CHANGE ***
		//*** ********************************************
		
		switch ($dataarray["fieldname"]){
			case "title": 
				$dataarray["fieldname"] = "Title_UsersDetails";
				break;
			case "forename":
				$dataarray["fieldname"] = "FirstName_UsersDetails";
				break;
			case "surname":
				$dataarray["fieldname"] = "LastName_UsersDetails";
				break;
			case "companyname":
				$dataarray["fieldname"] = "CompanyName_UsersDetails";				
				break;
			case "clientaddress":
				$dataarray["fieldname"] = "Address_UsersDetails";				
				break;
			case "city":
				$dataarray["fieldname"] = "City_UsersDetails";				
				break;			
			case "state_province_county":
				$dataarray["fieldname"] = "State_UsersDetails";				
				break;			
			case "zip":
				$dataarray["fieldname"] = "ZipCode_UsersDetails";				
				break;			
			case "country":
				$dataarray["fieldname"] = "Country_UsersDetails";				
				break;			
			case "phonenumber":
				$dataarray["fieldname"] = "DaytimePhone_UsersDetails";				
				break;			
			case "mobile":
				$dataarray["fieldname"] = "Mobile_UsersDetails";				
				break;			
			case "email":
				$dataarray["fieldname"] = "Email_UsersDetails";				
				break;			
			
		};
		
		//CREATING UPDATE DATA ARRAY
		$data = array ( $dataarray["fieldname"] => $dataarray["fieldvalue"] );
		
		//CREATING WHERE CLAUSE
		$this->db->where('id_Users', $dataarray["idusers"]);
		
		//EXECUTING QUERY AND STORE RESULT TO VAR
		$sql = $this->db->update('usersdetails', $data);

		if($dataarray["fieldname"] == 'Email_UsersDetails')
		{
			
			$dataarray["fieldname"] = "UserName_Users";
			
			$datauser = array ( $dataarray["fieldname"] => $dataarray["fieldvalue"] );
			
			$this->db->where('id_Users', $dataarray['idusers']);
			
			$sql = $this->db->update('users', $datauser);
			
		}

		//RETURN BOOLEAN VALUE ????????
        return $sql;		
	}

/***********************************
*   Backoffice functions
***********************************/

    //returns the list of insiders
    function admin_get_insiders_count()
    {
		return $this->db->count_all("users");
	}
    //returns the list of insiders
    function admin_get_list($fields='*', $limit=1000, $start=0)
    {
        $this->db->select($fields)
                ->from('users')
                ->join('usersdetails', 'users.id_Users = usersdetails.id_Users', 'left')
                ->order_by('FirstName_UsersDetails')
				->limit($limit, $start);  

        $query = $this->db->get();
        return $query->result_array();
    }  
    //returns the list of users registered in the last 7 days
    function admin_get_recent($fields='*', $days=30)
    {
        $this->db->select($fields)
                ->from('users')
                ->join('usersdetails', 'users.id_Users = usersdetails.id_Users', 'left')
                ->where('DateJoined_UsersDetails >=', date("Y-m-d H:i:s", strtotime("-".$days." days")))
                ->order_by('DateJoined_UsersDetails, FirstName_UsersDetails');  

        $query = $this->db->get();
        return $query->result_array();
    }           
    function admin_get_item($id=false, $fields='*')
    {
        $this->db->select($fields)
                ->from('users')
                ->join('usersdetails', 'users.id_Users = usersdetails.id_Users', 'left')
                ->where('users.id_Users', $id);  

        $query = $this->db->get();
        return  $query->row_array();
    }                        
    function admin_get_crm($id=false, $fields='*')
    {
        $this->db->select($fields)
                ->from('crm')
                ->where('id_Users', $id);  

        $query = $this->db->get();
        return  $query->row_array();
    }        
    function admin_update_crm($id=false, $data=array())
    {
        $item = $this->admin_get_crm($id);
        if (empty($item)){
            $data["id_Users"] = $id;
            $sql = $this->db->insert_string('crm', $data);
            $this->db->query($sql);
        } else {
            $this->db->where('id_Users', $id)
                    ->update('crm', $data);
        }                                                   
    }        
    function admin_get_viewed_products_by_user($id=false, $fields='products.id_Products AS id, products.Name_Products AS title, products.description_Products AS intro, products.Main_Image AS image ')
    {
        $this->db->select($fields)
                ->from('products_users')
                ->join('products', 'products_users.id_Products = products.id_Products', 'left')
                ->order_by('products.Name_Products')
                ->where('products_users.id_Users', $id);  

        $query = $this->db->get();
        return $query->result_array();
    }
    public function admin_update($id=FALSE, $users_data=array(), $userdetails_data=array()){

        $this->db->where('id_Users', $id)
                ->update('users', $users_data);

        if (!empty($userdetails_data)){
            $this->db->where('id_Users', $id)
                    ->update('usersdetails', $userdetails_data);
        }

    }                      
    public function admin_delete($id=FALSE){

        $tables = array(
                    'users', 
                    'usersdetails', 
                    'products_users',
                    'crm');        

        $this->db->where('id_Users', $id);
        $this->db->delete($tables);

    } 
    public function admin_search($string = FALSE, $fields = array(), $order = FALSE, $limit=1000)
    {
        $all_fields = $fields;
        $all_fields[] = "id_Users, FirstName_UsersDetails AS name, LastName_UsersDetails AS surname, DateJoined_UsersDetails, DateDeactivated_UsersDetails, LastLogin_UsersDetails, NumberLogins_UsersDetails";

        $this->db->select(implode(', ',$all_fields))
                ->from('usersdetails')
                ->order_by($order);

        $i=0;
        foreach($fields AS $field){

            if ($i==0) $this->db->where($field.' LIKE', '%'.$string.'%');
            else $this->db->or_where($field.' LIKE', '%'.$string.'%');

        $i++;
        }
		$this->db->limit($limit);
        
        $query = $this->db->get();
        return $query->result_array();
        
    }
    public function export()
    {
        $this->load->plugin('to_excel');
        $this->db->select('
            users.id_Users AS ID, 
            Title_UsersDetails AS Title, 
            FirstName_UsersDetails AS Name, 
            LastName_UsersDetails AS Surname, 
            CompanyName_UsersDetails AS "Company name", 
            Address_UsersDetails AS Address, 
            State_UsersDetails AS "State/Province/County*",    
            ZipCode_UsersDetails AS "ZIP/Postal Code",
            Country_UsersDetails AS "Country",
            DaytimePhone_UsersDetails AS "Phone number",
            Mobile_UsersDetails AS "Mobile phone",
            Email_UsersDetails AS "Email address",
            ProfessionalDesignations AS "Professional designation",
            MailingList_UsersDetails AS "Mailing list subscriber",
            DateJoined_UsersDetails AS "Registration date",
            DateDeactivated_UsersDetails AS "Deactivation date",     
            LastLogin_UsersDetails AS "Last login",
            NumberLogins_UsersDetails AS "Number of logins",
            Active_Users AS "Active user", 
            Approved_Users AS "Approved user"') 
                ->from('users')
                ->join('usersdetails', 'users.id_Users = usersdetails.id_Users', 'left');

        $query = $this->db->get();
        to_excel($query, 'de_ferranti_insiders_database');    
    }

}
    
    
/* End of file newsmodel.php */
/* Location: ./system/application/models/newsmodel.php */ 
